import React, { useState } from 'react';
import { Select, Spin, Tooltip, message } from 'antd';
import { useRequest, defaultFormatResult } from '@/hooks';
import { genID } from '@/utils/utils';
import IconFont from '@/components/IconFont';
import { DynamicTable } from '@/pages/TurnoverSetting/EntrySetting/components';
import { getDeviceList, getDeviceAll } from '../../../services';

const { Option } = Select;
/**
 * 设备
 */
const DeviceConfigTable = React.forwardRef(({ entryPersonnelCode, canAction, form }, ref) => {
    const [dataSource, setDataSource] = useState([]); // 表格数据源
    // 获取设备类型列表

    const deviceParam = { entryPersonnelCode, assetCategory: 'Webmaster' };
    const { data: deviceList = [] } = useRequest(() => getDeviceAll(deviceParam), {
        ...defaultFormatResult
    });

    // 获取电脑配置默认列表
    const { loading: computerConfigLoading } = useRequest(() => getDeviceList(entryPersonnelCode), {
        refreshDeps: [entryPersonnelCode],
        onSuccess: res => {
            const { code, msg, data } = res || {};
            if (code === 10000) {
                if (data) {
                    const newArr = [];
                    data.forEach(item => {
                        const newData = { ...item, key: genID(10), isValidatorPass: true };
                        newArr.push(newData);
                    });
                    setDataSource(newArr);
                }
            } else {
                message.error(msg);
            }
        }
    });
    // 型号
    const formatDeviceData = data => {
        if (typeof data === 'string') {
            const device = deviceList?.find(item => item.assetCode === data);
            if (device) {
                return device.assetModelList || [];
            }
            return [];
        }
        return [];
    };
    // 型号
    const formatModelData = (assetCode, modelCode) => {
        if (assetCode && modelCode) {
            const deviceData = deviceList.find(item => item.assetCode === assetCode);
            const modelData = deviceData?.assetModelList.find(item => item.modelCode === modelCode);
            if (modelData) {
                return modelData?.assetNumber || '';
            }
            return '';
        }
        return '';
    };

    const columns = [
        {
            title: '资产名称',
            dataIndex: 'assetCode',
            width: 180,
            editable: true,
            render: ({ text, fieldDecorator, setFieldsValue }) => (
                <>
                    {fieldDecorator('assetCode', {
                        initialValue: text,
                        rules: [
                            {
                                required: true,
                                message: '请选择'
                            }
                        ]
                    })(
                        <Select
                            style={{ width: '120px' }}
                            onSelect={selectValue => {
                                const option = deviceList.find(item => item.assetCode === selectValue) || {};
                                const { assetName, assetType, required = '1', assetCode, id } = option;
                                const assetNumber = formatModelData(assetCode, selectValue);
                                setFieldsValue({
                                    modelCode: undefined,
                                    assetName,
                                    assetType,
                                    required,
                                    assetNumber,
                                    id
                                });
                            }}
                            placeholder="请选择"
                            getPopupContainer={triggerNode => triggerNode.parentElement}
                            disabled={!canAction}
                        >
                            {deviceList &&
                                deviceList.map(item => (
                                    <Option value={item.assetCode} key={item.assetCode}>
                                        {item.assetName}
                                    </Option>
                                ))}
                        </Select>
                    )}
                </>
            )
        },
        {
            title: '资产型号',
            dataIndex: 'modelCode',
            editable: true,
            width: 240,
            render: ({ text, fieldDecorator, getFieldValue, setFieldValue }) => (
                <>
                    {fieldDecorator('modelCode', {
                        initialValue: text,
                        rules: [
                            {
                                required: true,
                                message: '请选择'
                            }
                        ]
                    })(
                        <Select
                            style={{ width: '200px' }}
                            placeholder="请选择"
                            disabled={!canAction}
                            onSelect={() => {
                                const assetNumber = formatModelData(
                                    getFieldValue('assetCode'),
                                    getFieldValue('modelCode')
                                );
                                setFieldValue('assetNumber', assetNumber);
                            }}
                        >
                            {formatDeviceData(getFieldValue('assetCode')).map(item => (
                                <Option value={item.modelCode} key={item.modelCode}>
                                    <Tooltip title={item.modelName}> {item.modelName}</Tooltip>
                                </Option>
                            ))}
                        </Select>
                    )}
                </>
            )
        },
        {
            title: '需求数量',
            dataIndex: 'required',
            width: 100,
            render: ({ fieldDecorator }) => (
                <>
                    {fieldDecorator('required', {
                        initialValue: '1'
                    })(<span>1</span>)}
                </>
            )
        },
        {
            title: '资产编号',
            dataIndex: 'assetNumber',
            width: 150,
            render: ({ text, fieldDecorator, getFieldValue }) => (
                <>
                    {fieldDecorator('assetNumber', {
                        initialValue: text
                    })(<span>{formatModelData(getFieldValue('assetCode'), getFieldValue('modelCode'))}</span>)}
                </>
            )
        },
        // {
        //     title: '可用库存',
        //     dataIndex: 'availableStock',
        //     width: 100,
        //     render: () => <span>-</span>
        // },
        // {
        //     title: '总库存',
        //     dataIndex: 'totalStock',
        //     width: 100,
        //     render: () => <span>-</span>
        // },
        {
            dataIndex: 'assetType',
            hide: true // 不展示, 但是需要记录的数据
        },
        {
            dataIndex: 'id',
            hide: true // 不展示, 但是需要记录的数据
        },
        {
            title: '操作',
            dataIndex: 'operator',
            width: 100,
            render: ({ index, methods }) => (
                <>
                    <IconFont
                        icon="iconDeleteIcon"
                        style={{ fontSize: '24px' }}
                        isButton
                        disabled={!canAction}
                        onClick={() => {
                            if (canAction) {
                                methods.remove(index);
                            }
                        }}
                    />
                </>
            )
        }
    ];

    return (
        <div ref={ref}>
            <div>请为新员工配置电脑及相关配件：</div>
            <Spin spinning={computerConfigLoading}>
                <DynamicTable
                    form={form}
                    initialValue={dataSource || []}
                    fieldName="assetList"
                    scroll
                    columns={columns}
                />
            </Spin>
        </div>
    );
});
export default DeviceConfigTable;
